package com.carlife.provider;

import java.util.ArrayList;
import java.util.List;

public class Conditions {
	
	public static final String ORDER_ASC = "ASC";
	public static final String ORDER_DESC = "DESC";
	
	private List<ConditionItem> condList = new ArrayList<ConditionItem>(2);
	private List<OrderItem> orderList = new ArrayList<OrderItem>(1);
	private String [] columns = null;
	private int limit = 0;
	
	public void addItem(ConditionItem item) {
		this.condList.add(item);
	}
	
	public void addOrder(String orderKey, boolean asc) {
		if (asc) {
			orderList.add(new OrderItem(orderKey, ORDER_ASC));
		} else {
			orderList.add(new OrderItem(orderKey, ORDER_DESC));
		}
	}
	
	public String [] getColumns() {
		return columns;
	}
	
	public void setColumns(String [] items) {
		this.columns = items;
	}
	
	public String getPrepareWhereClause() {		
		int condSize = condList.size();
		if (condSize == 0) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		
		ConditionItem [] items = new ConditionItem[condSize];
		items = (ConditionItem [])condList.toArray(items);
		for (int i = 0; i < items.length; i++) {
			if (i > 0) {
				buffer.append(" AND ");
			}
			buffer.append(items[i].getPrepareSql());
		}
		
		return buffer.toString();
	}
	
	public String [] getPrepareArguments() {
		int condSize = condList.size();
		if (condSize == 0) {
			return null;
		}
		String [] arguments = new String[condSize];
		
		ConditionItem [] items = new ConditionItem[condSize];
		items = (ConditionItem [])condList.toArray(items);
		for (int i = 0; i < items.length; i++) {
			arguments[i] = items[i].getValue().toString();
		}
		
		return arguments;
	}
	
	public String getFullWhereClause() {
		int condSize = condList.size();
		if (condSize == 0) {
			return null;
		}
		StringBuffer buffer = new StringBuffer();
		
		ConditionItem [] items = new ConditionItem[condSize];
		items = (ConditionItem [])condList.toArray(items);
		for (int i = 0; i < items.length; i++) {
			if (i > 0) {
				buffer.append(" AND ");
			}
			buffer.append(items[i].getFullSql());
		}
		
		return buffer.toString();
	}
	
	public String getOrderClause() {
		OrderItem [] items = new OrderItem[orderList.size()];
		items = (OrderItem [])orderList.toArray(items);
		
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < items.length; i++) {
			if (i>0) {
				buffer.append(",");
			}
			buffer.append(items[i]);			
		}
		
		return buffer.toString();
	}
	
	public int getLimit() {
		return this.limit;
	}
	
	public void setLimit(int rows) {
		this.limit = rows;
	}
	
	
	class OrderItem {
		private String key;
		private String orderType;
		
		public OrderItem(String key, String orderType) {
			super();
			this.key = key;
			this.orderType = orderType;
		}

		@Override
		public String toString() {
			return key + " " + orderType;
		}
		
		
	}

}
